package com.yx1996.bean.day02.cglib;

import com.yx1996.bean.day02.service.UserService;
import com.yx1996.bean.day02.service.UserServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib代理
 */
public class UserServiceProxyFactory2 implements MethodInterceptor {

    public UserService getUserService(){
        //生成代理对象
        Enhancer en = new Enhancer();
        en.setSuperclass(UserServiceImpl.class);
        //代理需要做什么
        en.setCallback(this);
        //生成代理完成的对象
        UserService usProxy = (UserService) en.create();

        return usProxy;
    }



    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("打开事务！！！");
        Object proxyValue = methodProxy.invokeSuper(o, objects);
        System.out.println("关闭事务！！！");
        return proxyValue;
    }
}
